<?php

namespace lxs\tools;

use Illuminate\Support\Facades\Redis;

class AuthToken
{

    protected string|array|null $token = null;
    protected mixed $uid = null;
    protected mixed $module = null;

    public function __construct($module = 'api')
    {
        $this->module = $module;
    }


    public function getToken(): array|string|null
    {
        if (!$this->token) {
            $this->token = request()->header('author');
        }
        return $this->token;
    }


    public function setToken($token): void
    {
        $this->token = $token;
    }


    public function checkToken(): bool
    {
        if (!$this->token) {
            $this->token = request()->header('authorization');
        }
        if (!$this->token) {
            $this->token = request()->input('token');
        }

        $uid = Redis::get($this->token);
        if ($uid) {
            $this->uid = $uid;
        }
        return !!$uid;
    }


    public function createToken($uid, $type=null, $expire = 86400 * 30): string
    {
        $iv = base64_encode(openssl_random_pseudo_bytes(openssl_cipher_iv_length('AES-256-CBC')));
        $token = uniqid(32) . $type . $iv;
        Redis::setEx($token, $expire, $uid);
        return $token;
    }


    public function getUid()
    {
        if (!$this->uid) {
            $this->uid = Redis::get($this->getToken());
        }
        return $this->uid;
    }


    public function destroyToken(): void
    {
        if ($this->token) {
            Redis::del($this->token);
        }
    }


}
